package com.yunshang.shoppingmall.shopping.productApi.controller;

import com.yunshang.shoppingmall.common.ProductGuigePriceUtil;
import com.yunshang.shoppingmall.entity.*;
import com.yunshang.shoppingmall.service.*;
import com.yunshang.shoppingmall.service.User.UserRankService;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/*商品详情*/
@Controller
@RequestMapping("/wap")
public class ProductDetailsController {

    @Autowired
    ProductGuigePriceService productGuigePriceService;
    @Autowired
    UserRankService userRankService;
    @Autowired
    ConfigService configService;
    @Autowired
    SysUserNoService sysUserNoService;
    @Autowired
    UserProductCommentService userProductCommentService;
    @Autowired
    OrderDetailsService orderDetailsService;
    @Autowired
    ProductGuiGeService productGuiGeService;
    @Autowired
    ProductService productService;




    /*根据商品Id查商品详情*/
    @ResponseBody
    @RequestMapping("/getDetails")
    public ModelAndView getProductDetail(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView("shoppingApi/product/productDetail");
        Map<String, Object> map = new HashMap<>();
        String productId = request.getParameter("productId");
        String guigeId = request.getParameter("guigeId");

        int guigeIds = 0;
        if (guigeId != null && guigeId != "") {
            guigeIds = Integer.parseInt(guigeId);
        }
        String ShareUserNoId = request.getParameter("userNoId");
        request.getSession().setAttribute("shareUserNoId", ShareUserNoId);
      if(ShareUserNoId!=null&&ShareUserNoId!=null){
          Cookie cookie=new Cookie("shareUserNoId",ShareUserNoId);
          response.addCookie(cookie);
      }
        if (productId == null || productId == "") {
            map.put("msg", "0");
            modelAndView.addObject("map", map);
            return modelAndView;
        }

        HttpSession session = request.getSession();

        if(session.getAttribute("subscribe")!=null)
        {
            map.put("subscribe", 1);
        }
        else
        {
            map.put("subscribe", null);
        }

        //根据商品id查询商品详情
        int productIds = 0;

        String guigeGroupImg = null;
        String[] guigeGroupImages = new String[20];
        String[] groupimages = new String[30];
        String[] guige_img = new String[30];
        String guige_img_group = null;
        List guige_img_list = new ArrayList();
        double fenXiangZhuan = 0.00;
        productIds = Integer.parseInt(productId);

        //分享跳转
        if(productIds==491){

            modelAndView=new ModelAndView("shoppingApi/product/activityDetail");
            UserNo userNo=(UserNo) request.getSession().getAttribute("userNo");
            map.put("userNo",userNo);
            map.put("productId",productId);
            modelAndView.addObject("map",map);
            return modelAndView;

        }

        ProductGuigePrice productGuigePrice = new ProductGuigePrice();
        productGuigePrice.setProductId(productIds);
        System.out.println("---->" + guigeIds);
        productGuigePrice.setGuigeId(guigeIds);
        map.put("productId", productIds);
        //按产品id和规格id查询商品
        List<ProductGuigePrice> productGuigePriceList = productGuigePriceService.selectProductGuigePriceById(productGuigePrice);
        //商品价格
        double proPrice = 0.00;
        //不同规格的商城价由低到高
        List proPriceList = new ArrayList();
        //优惠最低价格
        ProductGuigePrice productGuigePrice1 = null;
        //商品的描述
        String productDesc = null;
        String productName = null;

        //规格图组
        for (int i = 0; i < productGuigePriceList.size(); i++) {
//            System.out.println("------规格名称----->" + productGuigePriceList.get(i).getGuigeName());

            if (productGuigePriceList != null && productGuigePriceList.get(i) != null && productGuigePriceList.get(i).getProPrice() != null) {
                proPrice = productGuigePriceList.get(i).getProPrice().doubleValue();
                productGuigePrice1 = productGuigePriceList.get(i);
//                System.out.println("----详情图----->" + productGuigePrice1.getDetailContent());
            }
            if (productGuigePriceList != null && productGuigePriceList.get(i) != null && productGuigePriceList.get(i).getProPrice() != null) {
                double productPrice = productGuigePriceList.get(i).getProPrice().doubleValue();
                proPriceList.add(productPrice);
            }
        }

        //根据商品id查询规格
        productGuigePrice.setGuigeId(0);
        productGuigePrice.setUpstate("1");
        List<ProductGuigePrice> proGuigePriceList = productGuigePriceService.selectProductGuigePriceById(productGuigePrice);
        for (int i = 0; i < proGuigePriceList.size(); i++) {
            guigeGroupImages[i] = proGuigePriceList.get(i).getImgGroup();
        }

        //处理图组
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < guigeGroupImages.length; i++) {
            if (guigeGroupImages[i] != null && guigeGroupImages[i] != "") {
                sb.append(guigeGroupImages[i]);//合并所有的规格图
            } else {
                break;
            }
        }

        guige_img_group = sb.toString();
        if (guige_img_group != null) {
            guige_img = guige_img_group.split(",");
        }
        for (int i = 0; i < guige_img.length; i++) {
            if (guige_img[i].length() != 0) {
                guige_img_list.add(guige_img[i]);
            }

        }

        //优惠后最低价
        //登录用户
        int userRankId = 0;
        UserRank userRank = null;
        double commission = 0.00;
        double reCommendCommission = 0.00;//推荐人的提成比

        //提成比
        double yhcommission = 0.00;
        double ykcommission = 0.00;

        double newUserCommission = 0.00;//新用户的提成比
        List commissionarr = new ArrayList();
        UserNo userNo = (UserNo) request.getSession().getAttribute("userNo");

        if (userNo != null) {
            userRankId = userNo.getRank();
            userRank = userRankService.selectByPrimaryKey(userRankId);
            commission = userRank.getCommission();
//            System.out.println("登录用户提成比：" + commission);

            //新用户的提成比
            List<UserRank> userRankList = userRankService.selectUserRankList();
            //获取新用户的提成比

            for (int i = 0; i < userRankList.size(); i++) {

                commissionarr.add(userRankList.get(i).getCommission());

            }
            Collections.sort(commissionarr);

            newUserCommission = (double) commissionarr.get(0);
            if (commission <= newUserCommission) {
                newUserCommission = 0.00;
            }
//            System.out.println("newcomm---" + newUserCommission + "---" + commission);


        } else {//未登录
            List<UserRank> userRankList = userRankService.selectUserRankList();
            for (int i = 0; i < userRankList.size(); i++) {
                commissionarr.add(userRankList.get(i).getCommission());
            }
            Collections.sort(commissionarr);
            commission = (double) commissionarr.get(0);
//            System.out.println("未登录的默认提成比：" + commission);
            //分享赚
            commission = (double) commissionarr.get(0);
            newUserCommission = (double) commissionarr.get(0);

        }
        double minyhPrice = ProductGuigePriceUtil.getMinyhPrice(productGuigePrice1, commission);
//        System.out.println("最低优惠价：" + minyhPrice);
        //会员节省
        double hyJSheng = ProductGuigePriceUtil.getHyJSheng(productGuigePrice1, commission);
//        System.out.println("会员节省：" + hyJSheng);
        //分享赚
        fenXiangZhuan = ProductGuigePriceUtil.getFenXiangZhuan(productGuigePrice1, commission, newUserCommission);
//        System.out.println("分享赚：" + fenXiangZhuan);
        if (userNo == null) {
            fenXiangZhuan = ProductGuigePriceUtil.getFenXiangZhuan(productGuigePrice1, commission, newUserCommission);
//            System.out.println("提成比yk：" + yhcommission + "--" + ykcommission);
        }

        //不同规格的价格
        Collections.sort(proPriceList);
        double minProPrice = (double) proPriceList.get(0);
        double maxProPrice = (double) proPriceList.get(proPriceList.size() - 1);

        //商品评论
        UserProductComment userProductComment = null;
        List<UserProductComment> userProductCommentList = userProductCommentService.selectProductCommentList(productIds);
        if (userProductCommentList.size() != 0) {
            userProductComment = userProductCommentList.get(0);
        }
        //获取产品信息
        Product product=productService.selectByPrimaryKey(productIds);
        //产品是否可以有多地址
        int isMoreAddress=product.getIsMoreAddress()==null?0:product.getIsMoreAddress();

        //配置页面的名称
        Config configTemp = configService.selectByPrimaryKey(1);
        Config config=new Config();
        config.setFinacename1(configTemp.getFinacename1());
        config.setFinacename2(configTemp.getFinacename2());
        config.setFinacename3(configTemp.getFinacename3());
        config.setFinacename4(configTemp.getFinacename4());
        config.setGiftDiscount(configTemp.getGiftDiscount());
        map.put("isMoreAddress", isMoreAddress);
        map.put("guige_img_list", guige_img_list);
        map.put("proPrice", proPrice);
        map.put("minyhPrice", minyhPrice);
        map.put("productGuigePrice", productGuigePrice1);
        map.put("config", config);
        map.put("hyJSheng", hyJSheng);
        map.put("fenXiangZhuan", fenXiangZhuan);
        map.put("minProPrice", minProPrice);
        map.put("maxProPrice", maxProPrice);
        map.put("productGuigePriceList", productGuigePriceList);
        map.put("proGuigePriceList", proGuigePriceList);
        map.put("userProductComment", userProductComment);
        map.put("userNo", userNo);
        map.put("newUserCommission", newUserCommission);
        map.put("userCommission", commission);
        modelAndView.addObject("map", map);
        return modelAndView;
    }

    /*活动专区统计商品已下单付款的数量*/
    @ResponseBody
    @RequestMapping("/getPayOrderProductCount")
    public Map<String, Object> getPayOrderProductCount(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        UserNo userNo = (UserNo) request.getSession().getAttribute("userNo");
        int userNoId = 0;
        if (userNo != null) {
            userNoId = userNo.getId();
        }
        String productId=request.getParameter("productId");
        if(productId==null||productId==""){
            return map ;}
        String guigeId=request.getParameter("guigeId");
        if(guigeId==null||guigeId==""){return map;}
        int productIds=Integer.parseInt(productId);
        int guigeIds=Integer.parseInt(guigeId);
        String activeSign=request.getParameter("activeSign");
        //查询活动商品可以购买总数量
        ActiveProduct activeProduct = new ActiveProduct();
        activeProduct.setActiveSign(activeSign);
        activeProduct.setGuigeId(guigeIds);
        activeProduct.setProductId(productIds);
        int productTotalCount=0;//orderDetailsService.selectActiveProductTotalCount(activeProduct);
        System.out.println("用户已购总数----------------------"+productTotalCount);
        ProductGuiGe productGuiGe=productGuiGeService.selectByPrimaryKey(guigeIds);
        int buyCountTotal=0;//限购总数
        int buyCount=0;//每人限购数量
        if(productGuiGe!=null){
           buyCountTotal= productGuiGe.getBuyCountTotal();
           buyCount=productGuiGe.getBuyCount();
            System.out.println("每人限购数量---------------"+buyCount);
            System.out.println("限购总数量---------------"+buyCountTotal);
        }

        if(productTotalCount>buyCountTotal){
            map.put("msg",'0');
            map.put("buyCountTotal",buyCountTotal);
            return map;
        }
        activeProduct.setUserNoId(userNoId);
       List<OrderDetailsProduct> orderDetailsProductsList= orderDetailsService.selectActiveProductCount(activeProduct);
       int productSum=0;
        for (int i = 0; i <orderDetailsProductsList.size() ; i++) {
            if(orderDetailsProductsList!=null&&orderDetailsProductsList.size()!=0){
                productSum+=orderDetailsProductsList.get(i).getProductCount().intValue();
            }else{
                break;
            }
        }
        if(productSum>buyCount){
            map.put("msg","1");
            map.put("buyCount",buyCount);
            return map;
        }
        return map;
    }

    // 活动详情
    @ResponseBody
    @RequestMapping("/activity")
    public ModelAndView transfer(HttpServletRequest request) {
        String htmlName="shoppingApi/product/activityDetail";
        ModelAndView modelAndView=new ModelAndView(htmlName);
        Map<String,Object> map=new HashMap<>();
        String productId=request.getParameter("productId");
        map.put("productId",productId);
        UserNo userNo=(UserNo) request.getSession().getAttribute("userNo");
        System.out.println("userNo---"+userNo);
        map.put("userNo",userNo);
        modelAndView.addObject("map",map);
        return  modelAndView;
    }

}
